'''
PDF生成模块,需要安装wkhtmltopdf软件，首先生成HTML表格，然后转换为PDF
example:
ubuntu: sudo apt-get install wkhtmltopdf
centos: yum install wkhtmltopdf
'''

import pdfkit
from datastore import datastore
from model.models import modelWordCount
import statistics 
import os

class pdfCreator:
    PDF_NAME = r'data/wordlist.pdf'
    HTML_NAME = r'data/wordlist.html'
    def __init__(self):
        self.datastore = datastore()

    def generateWordList(self, number):        
        words = self.datastore.getTopNWords(number)
        cnt = 1
        with open(pdfCreator.HTML_NAME, 'w') as f:
            f.write('<html>')
            f.write('<head><meta charset="UTF-8"></head>')
            f.write('<body>')            
            f.write('<p>共统计{}单词，Top{}单词表</p>'.format(statistics.getWordCount(), number))
            f.write(r'<table border="1">') 
            f.write('<tr>')
            f.write('<th>'+ '序号' + '</th>')
            f.write('<th>'+ '词频' + '</th>')
            f.write('<th>'+ '单词' + '</th>')
            f.write('<th>'+ '释义' + '</th>')
            f.write('</tr>')
            for word in words:
                f.write('<tr>')
                f.write('<td>' + 'No.{}'.format(cnt) + '</td>')
                f.write('<td>' + str(word.count) + '</td>')
                f.write('<td>' + word.word + '</td>')
                if word.trans:
                    f.write('<td>' + word.trans + '</td>')
                else:
                    f.write('<td>N/A</td>')
                f.write('</tr>')
                cnt += 1
            f.write('</table>')
            f.write('</body>')
            f.write('</html>')

        pdfkit.from_file(pdfCreator.HTML_NAME, pdfCreator.PDF_NAME)
        os.remove(pdfCreator.HTML_NAME)
        
if __name__ == '__main__':
    a = pdfCreator()
    a.generateWordList(5000)
    